package com.lu.aio.server;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.lu.aio.ChannelAdapter;
import com.lu.aio.ChannelHandler;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.Selector;
import java.util.Date;

/**
 * @program lu-netty
 * @description:
 * @author: zhanglu
 * @create: 2022-06-10 17:30:00
 */
@Slf4j
public class AioServerHandler extends ChannelAdapter {

    public AioServerHandler(AsynchronousSocketChannel channel, String charset) {
        super(channel, charset);
    }

    @Override
    protected void channelActive(ChannelHandler ctx) {
        try {
            log.info("{} 加入连接", ctx.channel().getRemoteAddress());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void channelInactive(ChannelHandler ctx) {

    }

    @Override
    protected void channelRead(ChannelHandler ctx, Object msg) {
        String currentDate = DateUtil.format(new Date(), DatePattern.NORM_DATETIME_PATTERN);
        log.info(StrUtil.format("{} --- 接收消息：{}", currentDate, msg));
        ctx.writeAndFlush(StrUtil.format("client-request:{} received", msg));
    }

}
